<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Public_Controller extends Controller {
	public $iTimeEpoch;
	public $sSkinPath;
	public $sSkinFile;
	public $sPlatform;
	public $sPageTitle;
	public $sPageKeywords;
	public $sPageDesc;
	public $sPageContainer;
	public $sPageSubContainer;
	public $sPageHeader;
	public $aPageJs = array();
	public $aPageCss = array();
	public $aMessages = array();
	public $aData = array();
	
	public $iDomainId = 0;
	public $sDomainBase = null;
	public $iPageId;
	public $iPageDataId;
	public $iTopLevelPageId = 0;
	public $iTopLevelSelectedPageId = 0;
	public $iPageMainContentWidth = 900;
	

	public $oSecGroup = false;
	
	/**
	 * Constructor
	 *
	 * Calls the parent construct, preloads loads some necessary libraries and 
	 * autoloads the necessary CSS and JS files needed for the page
	 */
  	function __construct() 
	{
    	parent::Controller();
		
		
		if ($this->config->item('ci_profiler_enabled') === true)
		{
			if ($this->display_profiler() === true)
			{
				$this->output->enable_profiler($this->config->item('ci_profiler_enabled'));		
			}
		}
		
		
		$this->iTimeEpoch = time();
		
		//set the default skin path and file
		$this->sSkinPath = $this->config->item('default_skin_path');
		$this->sSkinFile = $this->config->item('default_skin_file');
		$this->sSkinMediaPath = $this->config->item('default_skin_media_path');
		$this->sPlatform = $this->config->item('default_platform_name');
		$this->sPageTitle = $this->config->item('site_page_title');
		$this->sPageContainer = $this->config->item('default_page_container');
		$this->sPageSubContainer = $this->config->item('default_page_subcontainer');
		
		$this->load->model('user');
		
		if ($this->user->userId !== false)
		{
			// set the users security group
			$this->load->model('db/views/user_security_group', 'vw_user_security_group');
			
			$this->vw_user_security_group->user_id = $this->user->userId;
			
			$qSecGroup = $this->vw_user_security_group->get();
			
			$this->aData['qSecGroup'] = $qSecGroup;
			
			if ($qSecGroup->num_rows() > 0)
			{
				$this->oSecGroup = $qSecGroup->row(0);	
			}
		}
		
		$this->process_site_messages();
	}
	
	private function display_profiler() 
	{
		$aUri = $this->uri->segment_array();
		$iUri = count($aUri);
	
		if ($iUri === 0)
		{
			return true;	
		} 
		else if ($iUri > 0)
		{			
			if ($aUri[1] !== 'media') 
			{
				if (($iUri > 1) && (substr($aUri[2], -5) !== '_ajax'))
				{
					return true;
				}	
			}
		}
		
		
		return false;
		
			
	}
	
	
	
	public function jsonify_string($sStr, $bAddSlashes = false)
	{
		$sStr = preg_replace('/\s\s+/', ' ', $sStr);
		$sStr = preg_replace('/\r?\n/m', '', $sStr);
		$sStr = preg_replace('/\t/m', '', $sStr);
		
		if ($bAddSlashes === true) 
		{
			$sStr = addslashes($sStr);
		}
		
		return $sStr;
	}
	
	
	
	public function cast_array_to_object($aArr)
	{
		$oRet = new stdClass();

		foreach ($aArr as $vKey => $vVal) 
		{
	
			if (is_array($vVal)) 
			{
				$oRet->$vKey = $this->cast_array_to_object($vVal);
			}
			else 
			{
				$oRet->$vKey = $vVal;
			}
		}
		return $oRet;
	}
	

	protected function process_site_messages($bAddSlashes = false)
	{
		$this->load->model('db/messages', 'tbl_messages');
		
		$qMessages = $this->tbl_messages->get();
		$iMessages = $qMessages->num_rows();
		
		
		
		for ($i = 0; $i < $iMessages; $i++)
		{
			if ($bAddSlashes === true)
			{
				$qMessages->row($i)->message_default = addslashes($qMessages->row($i)->message_default);
			}
			
			$this->aMessages[$qMessages->row($i)->message_ident] = $qMessages->row($i)->message_default;
		}
		
		$this->aData['aMessages'] = $this->aMessages;
	}
	
	
	
	public function get_site_message($sIdent = '', $bAddSlashes = false)
	{
		if (array_key_exists($sIdent, $this->aMessages) === false)
		{
			return 'unknown_label';
		}
		
		if ($bAddSlashes === true)
		{
			return addslashes($this->aMessages[$sIdent]);
		}
		
		return $this->aMessages[$sIdent];
	}
	
	public function process_page_menu_top()
	{
		$this->load->model('db/views/page_menus', 'vw_page_menus');
		
		$this->vw_page_menus->clear();
		$this->vw_page_menus->page_id = $this->iPageId;
		$this->vw_page_menus->menu_id = 1;
		$this->vw_page_menus->page_data_menu_type = 'H';
		
		$qHasMenu = $this->vw_page_menus->get(array(), 1);
		
		
		$this->vw_page_menus->clear();
		
		if ($qHasMenu->num_rows() === 1)
		{
			$this->load->library('pages_lib');
			
			$aTopMenu = $this->pages_lib->get_page_menu($this->iTopLevelPageId, 1, 0, 2);
			
			$sContent = $this->pages_lib->build_page_tree($aTopMenu, 0);
		
			$sContent = $this->load->view('platform/'.$this->sPlatform.'/top_menu_ul_wrapper', array('sContent' => $sContent), true);

			return $sContent;
		}
		
		return '';
	}
	
	
	public function process_page_menu_left()
	{
		$sContent = $sExtraContent = '';
		
		$this->load->model('db/page_data_menus', 'page_data_menus');
		
		$this->page_data_menus->page_data_id = $this->iPageDataId;
		$this->page_data_menus->menu_id = 2;
		$this->page_data_menus->page_data_menu_type = 'H';

		$qPageMenu = $this->page_data_menus->get(1);
		
		if ($qPageMenu->num_rows() > 0)
		{
			$this->load->model('db/views/page_menus', 'vw_page_menus');
			$this->vw_page_menus->clear();
			
			$this->load->library('pages_lib');
				
			//$aLeftMenu = $this->pages_lib->get_page_menu($this->iPageId, 2, 0, 0);
			
			$aLeftMenu = $this->pages_lib->get_page_menu(false, 2, 0, 0);
				
			if (count($aLeftMenu) > 0)
			{
				$sContent = $this->pages_lib->build_page_menu($aLeftMenu, 0);
			
				$sContent = $this->load->view('platform/'.$this->sPlatform.'/left_menu_ul_wrapper', array('sContent' => $sContent, 'bHeader' => true), true);
				
			}
		}				
		
		$sContent .= $sExtraContent;		
		
		
		return $sContent;
	}
	
	public function process_page_breadcrumb($iPageId = null)
	{
		$this->load->model('db/views/page_menus', 'vw_page_menus');
		
		$bHasParent = true;
		
		$this->vw_page_menus->clear();
		
		if ($iPageId === null)
		{
			$iPageId = $this->iPageId;	
		}
		
		$aBreadCrumb = $this->vw_page_menus->get_breadcrumb($this->iPageId);
		
		$this->aData['aBreadCrumb'] = $aBreadCrumb;
		
		return $this->load->view('platform/'.$this->sPlatform.'/breadcrumb', $this->aData, true);
	}
	
	public function process_page_inner_title()
	{
		return $this->load->view('platform/'.$this->sPlatform.'/inner_title', array('sPageTitle' => $this->sPageTitle), true);
	}
	
	public function process_page_footer()
	{
		return $this->load->view('platform/'.$this->sPlatform.'/footer', $this->aData, true);
	}
	
	public function process_page_js()
	{
		$sJsFile = '';
		
		foreach($this->aPageJs as $oPageJs)
		{
			if (is_array($oPageJs) === true) // if it's an array
			{
				if ((array_key_exists('combine_js', $oPageJs) === true) && ($this->config->item('combine_js') === true)) // if we're combining the javascript
				{
					$sJsFile .= $this->config->item('js_ext_prefix');
					
					if($this->config->item('js_cdn') !== false && substr($oPageJs['base_href'], 0, 10) === '/assets/js')
					{
						//$sJsFile .= (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $this->remove_subdomain($_SERVER['HTTP_HOST'], 'js.');
					}
					
					$sJsFile .= $oPageJs['base_href'];
					
					if (substr($sJsFile, -1) !== '/')
					{
						$sJsFile .= '/';
					}
					
					$sJsFile .= urlencode(join($this->config->item('media_func_sep'), $oPageJs['js']));
					
					if (array_key_exists('version', $oPageJs) === true)
					{
						$sJsFile .= '/'.$oPageJs['version'];
					}
					
					$sJsFile .= $this->config->item('js_ext').$this->config->item('js_ext_suffix');
					
					
				}
				else // we're not combining the javascript 
				{
					$iJsFiles = count($oPageJs['js']);
					
					for ($i = 0; $i < $iJsFiles; $i++)
					{
						$sJsFile .= $this->config->item('js_ext_prefix').$this->config->item('js_cdn').$oPageJs['base_href'].'/';
						
						if (substr($oPageJs['js'][$i], 0 - strlen($this->config->item('js_ext'))) === $this->config->item('js_ext'))
						{
							$oPageJs['js'][$i] = substr($oPageJs['js'][$i], 0, 0 - strlen($this->config->item('js_ext')));
						}
						
						if (array_key_exists('version', $oPageJs) === true)
						{
							$oPageJs['js'][$i] .= '/'.$oPageJs['version'];
						}
						
						$sJsFile .= $oPageJs['js'][$i];
						
						if (array_key_exists('ignore_ext', $oPageJs) === false) {
							$sJsFile .= $this->config->item('js_ext');
						}
						
						$sJsFile .= $this->config->item('js_ext_suffix');
						
					}
				}
			}
			else 
			{
				
				$sJsFile .= $this->config->item('js_int_prefix').$oPageJs.$this->config->item('js_int_suffix');
				
			}
			
			
		}
		
		
		return $sJsFile;
		
		
	}
	
	
	
	public function process_page_css()
	{
		$aCssFile = array();
		$iCssFile = 0;
		$sCssFile = '';
		$sCssMedia = '';
		
		$sDomain = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];
		
		
		foreach($this->aPageCss as $oPageCss)
		{
			$sCssMedia = $oPageCss['media'];
			
			if (is_array($oPageCss) === true) // if it's an array
			{
				if ((array_key_exists('combine_css', $oPageCss) === true) && ($this->config->item('combine_css') === true)) // if we're combining the css
				{
					
					$sCssFile = $oPageCss['base_href'];
					
					if($this->config->item('css_cdn') !== false && substr($sCssFile, 0, 1) === '/')
					{
						
						$sCssFile = $sDomain . $sCssFile;
					}
					
					if (substr($sCssFile, -1) !== '/')
					{
						$sCssFile .= '/';
					}
					
					$sCssFile .= urlencode(join($this->config->item('media_func_sep'), $oPageCss['css']));
					
					if (array_key_exists('version', $oPageCss) === true)
					{
						$sCssFile .= '/'.$oPageCss['version'];
					}
					
					
					$aCssFile[$iCssFile] = str_replace('{media}', $sCssMedia, $this->config->item('css_syntax'));
					$aCssFile[$iCssFile] = str_replace('{href}', $sCssFile.$this->config->item('css_ext'), $aCssFile[$iCssFile]);
					

					
					$iCssFile++;
					
				}
				else // we're not combining the javascript 
				{
					$iCssFiles = count($oPageCss['css']);
					
					for ($i = 0; $i < $iCssFiles; $i++)
					{

						$sCssHref = $oPageCss['base_href'];
						
						if($this->config->item('css_cdn') !== false && substr($sCssFile, 0, 1) === '/')
						{
							$sCssHref = $sDomain . $sCssHref;
						}
					
						if (substr($sCssHref, -1) !== '/')
						{
							$sCssHref .= '/';
						}
						
						$sCssHref .= $oPageCss['css'][$i];
						
						if (array_key_exists('version', $oPageCss) === true)
						{
							$sCssHref .= '/'.$oPageCss['version'];
						}
					
						$sCssHref .= $this->config->item('css_ext');
						
						
						//$config['css_syntax'] = '<link rel="stylesheet" type="text/css" media="{media}" href="{href}" />'
						$sCssFileTmp = $this->config->item('css_syntax');
						$sCssFileTmp = str_replace('{media}', $sCssMedia, $sCssFileTmp);
						$sCssFileTmp = str_replace('{href}', $sCssHref, $sCssFileTmp);
						
						$aCssFile[] = $sCssFileTmp;
					}

				}
			}
			
			
		}
		
		
		return join(chr(10), $aCssFile);
		
				
	}
} 





class Restricted_Controller extends Public_Controller {
		
	
  	function __construct() 
	{
    	parent::__construct();
	}		
	
	protected function user_logged_in($sLoadView = '', $aPageJs = array(), $aPageCss = array(), $sPageTitle = '', $bIsAdmin = false, $sSkin = 'admin')
	{
		if ($this->user->userId === false)
		{
			if (strtolower($this->input->server('REQUEST_METHOD')) === 'post')
			{
				$qUser = $this->check_credentials();
				
				if ($qUser === false)
				{
					$this->aData['sErrorMessage'] = $this->aMessages['admin_login_invalid_credentials'];
				}
				else 
				{
					if($qUser->row(0)->user_varified == 0)
					{
						$this->aData['sErrorMessage'] = 'Please varify your account. <a href="'.site_url("account/resend_varifier/".base64_encode($qUser->row(0)->user_id)).'">Click to resnd varification email.</a>';
					}
					else
					{
						$this->session->set_userdata('userId', $qUser->row(0)->user_id);
						$this->session->set_userdata('userName', $qUser->row(0)->user_fname);
						$this->session->set_userdata('userFullName', $qUser->row(0)->user_fname." ".$qUser->row(0)->user_lname);
						$this->session->set_userdata('userEmail', $qUser->row(0)->user_email);
						$this->session->set_userdata('userDatetime', $qUser->row(0)->user_datetime);
						
						redirect($this->uri->uri_string(), 'location');	
					}
				}
			}
			
			$this->sSkinFile = $sSkin;
			
			if(!empty($aPageJs))
			{
				$this->aPageJs[] = $aPageJs;	
			}
			
			if(!empty($aPageCss))
			{
				$this->aPageCss[] = $aPageCss;		
			}
			
			$this->sPageTitle = $sPageTitle;
			
			$this->load->view($sLoadView, $this->aData);
			$this->output->process_display();
			
			exit();
		} 
	}
	
	
	
	
	protected function intranet_log_in() 
	{
		
		
		/************************************************
		* check to see if the user is logged in - start *
		************************************************/
		$aPageJs = array(
							'combine_js' => true,
							'base_href' => '/media/js',
							'js' => array('jquery', 'admin_login'),
							'version' => '1.0'
		);	

		// build up our header_css array
		$aPageCss = array(
							'combine_css' => true,
							'base_href' => '/media/css',
							'css' => array('reset', 'admin_main', 'admin_login'),
							'media' => 'all',
							'version' => '1.0'
		);		
		
		$this->user_logged_in('platform/'.$this->sPlatform.'/admin/login', $aPageJs, $aPageCss, $this->aMessages['admin_login_title']);
		/**********************************************
		* check to see if the user is logged in - end *
		**********************************************/	
	}
	
	
	
	
	
	protected function access_rights_check($sLoadView = '', $aPageJs = array(), $aPageCss = array(), $sPageTitle = '', $sErrorMessage = '')
	{
		$this->load->library('access_rights');
		
		if ($this->access_rights->check_access($this->user->userId) === false)
		{
			$this->aPageJs[] = $aPageJs;	

			// build up our header_css array
			$this->aPageCss[] = $aPageCss;		
			
			
			$this->sPageTitle = $sPageTitle;
			
			if ($sErrorMessage !== '')
			{
				$this->aData['sErrorMessage'] = $sErrorMessage;
			}
			
			$this->load->view($sLoadView, $this->aData);
			$this->output->process_display();
			// exit gracefully
			exit();
		}
	}
	


	protected function check_credentials()
	{
		$this->load->model('db/users', 'users');
		
		// firstly check whether someone is trying to login with their username and password
		$this->users->user_login = $this->input->post('login_username', true, '');
		$this->users->user_passwd = md5($this->input->post('login_password', true, ''));
				
		$qUser = $this->users->get(array(), 1);
				
		if ($qUser->num_rows() === 1)
		{
			return $qUser;
		}
		
		// then check whether their using their email and password
		$this->users->user_email = $this->users->user_login;
		$this->users->user_login = false;

		$qUser = $this->users->get(array(), 1);
				
		if ($qUser->num_rows() === 1)
		{
			return $qUser;
		}

		// if we've not got a user, return null;
		return false;

	}
	
	


}



class Admin_Controller extends Restricted_Controller {
	
	
  	function __construct() {
    	parent::__construct();
		
		
		$this->admin_login();
			
		$this->aPageJs[] = array(
							'combine_js' => true,
							'base_href' => '/media/js',
							'js' => array('jquery', 'jquery_impromptu', 'admin_generic'),
							'version' => '1.1'
		);	

		// build up our header_css array
		$this->aPageCss[] = array(
							'combine_css' => true,
							'base_href' => '/media/css',
							'css' => array('reset', 'jquery_impromptu', 'admin_main', 'admin_top_nav', 'admin_top_menu', 'admin_home', 'admin_footer'),
							'media' => 'all',
							'version' => '1.1'
		);					
		
		
		$this->load->model('db/views/user_admin_apps', 'vw_user_admin_apps');
		
		$this->vw_user_admin_apps->user_id = $this->user->userId;
		$this->vw_user_admin_apps->app_installed = 'Y';
			
		$qApps = $this->vw_user_admin_apps->get();
			
		$this->aData['qApps'] = $qApps;



		
		/******************************
		* access rights check - start *
		******************************/
		
		$aPageJs = array(
							'combine_js' => true,
							'base_href' => '/media/js',
							'js' => array('jquery', 'admin_login'),
							'version' => '1.0'
		);	

		// build up our header_css array
		$aPageCss = array(
							'combine_css' => true,
							'base_href' => '/media/css',
							'css' => array('reset', 'admin_main', 'admin_login'),
							'media' => 'all',
							'version' => '1.0'
		);	
		
		$this->access_rights_check('platform/'.$this->sPlatform.'/admin/login', $aPageJs, $aPageCss, $this->aMessages['admin_login_title'], $this->aMessages['admin_user_not_authorised']);
		
		
		/****************************
		* access rights check - end *
		****************************/
		
		
	}	
	

	protected function admin_login() 
	{
		$this->sSkinFile = 'admin';
		
		
		/************************************************
		* check to see if the user is logged in - start *
		************************************************/
		$aPageJs = array(
							'combine_js' => true,
							'base_href' => '/media/js',
							'js' => array('jquery', 'admin_login'),
							'version' => '1.0'
		);	

		// build up our header_css array
		$aPageCss = array(
							'combine_css' => true,
							'base_href' => '/media/css',
							'css' => array('reset', 'admin_main', 'admin_login'),
							'media' => 'all',
							'version' => '1.0'
		);		
		
		$this->user_logged_in('platform/'.$this->sPlatform.'/admin/login', $aPageJs, $aPageCss, $this->aMessages['admin_login_title'], true);
		/**********************************************
		* check to see if the user is logged in - end *
		**********************************************/	
	}
	
	public function process_admin_header()
	{
		if ($this->user->userId !== false)
		{	
			return $this->load->view('platform/'.$this->sPlatform.'/admin/header', $this->aData, true);
		}
		
	}
	
	public function process_admin_footer()
	{
		if ($this->user->userId !== false)
		{	
			return $this->load->view('platform/'.$this->sPlatform.'/admin/footer', $this->aData, true);
		}
		
	}
	
	public function process_admin_menu()
	{
		if ($this->user->userId !== false)
		{	
			return $this->load->view('platform/'.$this->sPlatform.'/admin/menu', $this->aData, true);
		}
		
	}
}


?>